package com.lemon.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.PageResult;
import com.lemon.domain.User;
import com.lemon.domain.WarehousingEntryDetails;
import com.lemon.domain.dto.WarehousingDto;
import com.lemon.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.domain.WarehousingEntry;
import com.lemon.service.WarehousingEntryService;
@Service
@RequiredArgsConstructor
public class WarehousingEntryServiceImpl extends ServiceImpl<WarehousingEntryMapper, WarehousingEntry> implements WarehousingEntryService{
    private final WarehousingEntryMapper warehousingEntryMapper;
    private final WarehousingEntryDetailsMapper warehousingEntryDetailsMapper;
    private final UserMapper userMapper;
    private final WarehouseMapper warehouseMapper;
    private final SupplierMapper supplierMapper;

    @Override
    public PageResult getPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<WarehousingEntry> warehousingEntries = this.list();
        Page pageInfo = (Page) warehousingEntries;
        return new PageResult(pageInfo.getTotal(),pageInfo.getResult());
    }

    @Override
    public void add(WarehousingDto dto) {
        WarehousingEntry entry = new WarehousingEntry();
        entry.setBatchNumber(dto.getBatchNumber());
        entry.setConsignorId(Long.valueOf(dto.getConsignorId()));
        entry.setPredictedArrivalTime(dto.getPredictedArrivalTime());
        entry.setWarehouseId(dto.getWarehouseId());
        User user = userMapper.selectById(dto.getConsignorId());
        entry.setCreateTime(LocalDateTime.now());
        entry.setConsignorName(user.getName());
        entry.setWarehouseName(warehouseMapper.selectById(dto.getWarehouseId()).getName());
        entry.setStatus(1);
        warehousingEntryMapper.insert(entry);
        dto.getItems().forEach(item -> {
            WarehousingEntryDetails details = new WarehousingEntryDetails();
            details.setSkuId(Long.valueOf(item.getId()));
            details.setCode(item.getCode());
            details.setTitle(item.getTitle());
            details.setSupplierId(Long.valueOf(item.getSupplierId()));
            details.setSupplierName(supplierMapper.selectById(item.getSupplierId()).getSupplierName());
            details.setWarehousingEntryId(entry.getId());
            details.setCreateTime(LocalDateTime.now());
            details.setPredictedArrivalTime(dto.getPredictedArrivalTime());
            details.setStatus(1);
            warehousingEntryDetailsMapper.insert(details);
        });
    }
}
